#include "posview.h"
#include <QMimeData>
#include <QDebug>
#include <QMessageBox>

PosView::PosView(QGraphicsScene *scene, QWidget *parent) :
    QGraphicsView(scene, parent),
    xSaleStep(1),
    ySaleStep(1),
    xOld(1),
    yOld(1),
    current_show_type(SHOW_TYPE_ALL),
    numShowEnable(false)
{
    setAcceptDrops(true);
    scene->addItem(new QGraphicsTextItem("可选择拖入文件"));
}

PosView::PosView(QWidget *parent) :
    QGraphicsView(parent),
    xSaleStep(0.01),
    ySaleStep(0.01),
    xOld(1),
    yOld(1),
    current_show_type(SHOW_TYPE_ALL),
    numShowEnable(false)
{
    setAcceptDrops(true);
}

PosView::~PosView()
{

}

//鼠标滚轮事件
void PosView::wheelEvent(QWheelEvent *event)
{
    QPoint numDegrees = event->angleDelta();

    if (!numDegrees.isNull()) {
      if( numDegrees.y()>0.00001 ){
          xOld += xSaleStep;
          yOld += ySaleStep;
          if(xOld>20 || yOld>20) {
              xOld = 20;
              yOld = 20;
             centerOn(mouseCurrentPoint);
             return;
          }
          scale(1.1, 1.1);
      }else if( numDegrees.y()<-0.00001 ){
          xOld -= xSaleStep;
          yOld -= ySaleStep;
          if( xOld<0.05|| yOld<0.05 ){
              xOld = 0.05;
              yOld = 0.05;
              centerOn(mouseCurrentPoint);
              return;
           }
          scale(0.9, 0.9);
      }
      centerOn(mouseCurrentPoint);
    }

    event->accept();
}

//鼠标移动事件，为放大提供基准显示位置
void PosView::mouseMoveEvent(QMouseEvent *event)
{
    mouseCurrentPoint = event->localPos();

    emit sendMsg(getMouseUpMsg());

    event->accept();
}

//鼠标拖拽事件，直接读取文件
void PosView::dragEnterEvent(QDragEnterEvent *event)
{
    const QMimeData* md = event->mimeData();
    QString name = md->text();

    QStringList list = name.split(":///",QString::SkipEmptyParts);

    readPosFromFile(list[1]);

    event->acceptProposedAction();
    event->accept();
}

//拖拽结束事件，目前有问题
void PosView::dropEvent(QDropEvent *event)
{
    const QMimeData* md = event->mimeData();
    QString name = md->text();

    qDebug()<<"File Name: "<<name;

    if( readPosFromFile(name) ){
        currenShowFileName = name;
        emit fileListChange(true);
    }else{
        QMessageBox msgBox;
        msgBox.setText("File Error!");
        msgBox.exec();
    }

    event->accept();
}

//设置放大缩小步进值
void PosView::setScaleStep(qreal x, qreal y)
{
    xSaleStep = x;
    ySaleStep = y;
}

//读取pos文件，并且显示
bool PosView::readPosFromFile(QString &fn)
{
    if( fn.isNull() || fn.isEmpty() ) {
        QMessageBox msgBox;
        msgBox.setText("File Error!");
        msgBox.exec();
        return false;
    }

    if( QFile::exists(fn) ){
        PosFileInfo fileInfo(fn);
        if( fileInfo.readPos() ){
            posList[fn] = fileInfo;
            updateShow(fn);
            currenShowFileName = fn;
            emit fileListChange(true);
            return true;
        }
    }else{
        QMessageBox msgBox;
        msgBox.setText("File Error!");
        msgBox.exec();
    }

    return false;
}

//更新显示
bool PosView::updateShow(const QString& name)
{
    if( posList.keys().contains(name) ){
        PosFileInfo info = posList[name];
        QMap<QString, QPointF> points = info.getPoints();
        QMapIterator<QString, QPointF> i(points);
        qreal refx = 0.0, refy = 0.0;
        bool haveRef = false;

        cleanShow();

        while (i.hasNext()) {
          i.next();
          if( !haveRef ){
              QStringList list = i.key().split('-', QString::SkipEmptyParts);
              if( "1"==list[2] ){
                  refx = i.value().x();
                  refy = i.value().y();
                  haveRef = true;
              }
          }
          if(haveRef){
              QStringList list = i.key().split('-', QString::SkipEmptyParts);
              QGraphicsEllipseItem* it = nullptr;
              Qt::GlobalColor color;
              if( list[3]=="1" && ( current_show_type==SHOW_TYPE::SHOW_TYPE_ALL ||  current_show_type==SHOW_TYPE::SHOW_TYPE_FIX)){
                  color = Qt::darkGreen;
                  it = new QGraphicsEllipseItem(i.value().x()-refx, i.value().y()-refy, 2, 2);
              }else if( list[3]=="2" && ( current_show_type==SHOW_TYPE::SHOW_TYPE_ALL ||  current_show_type==SHOW_TYPE::SHOW_TYPE_FLOAT)){
                  color = Qt::yellow;
                  it = new QGraphicsEllipseItem(i.value().x()-refx, i.value().y()-refy, 2, 2);
              }else if( list[3]=="5" && ( current_show_type==SHOW_TYPE::SHOW_TYPE_ALL ||  current_show_type==SHOW_TYPE::SHOW_TYPE_SIGNLE)){
                  color = Qt::darkRed;
                  it = new QGraphicsEllipseItem(i.value().x()-refx, i.value().y()-refy, 2, 2);
              }

              if( it!=nullptr ){
                  it->setBrush(QBrush(color));
                  it->setPen(QPen(color));
                  ellipseItems.append(it);
                  scene()->addItem(it);
              }

              if( numShowEnable ){
                  QGraphicsTextItem* tit = new QGraphicsTextItem(list[2]);
                  tit->setFont(QFont("Consolas", 3, 1));
                  textItems.append(tit);
                  scene()->addItem(tit);
                  tit->setPos(i.value().x()-refx, i.value().y()-refy);
              }

              //qDebug()<<"x"<<QString::number(i.value().x())<<"y"<<QString::number(i.value().y());
          }
        }
        centerOn(refx, refy);
    }
    return true;
}

//清楚显示
void PosView::cleanShow()
{
    scene()->clear();

    /*
    qint64 len = textItems.length();
    for( qint64 i=0; i<len; ++i ){
        QGraphicsTextItem* t = textItems[i];
        delete t;
    }*/
    textItems.clear();

    /*
    len = ellipseItems.length();
    for( qint64 i=0; i<len; ++i ){
        QGraphicsEllipseItem* t = ellipseItems[i];
        delete t;
    }
    */
    ellipseItems.clear();
}

void PosView::showType(PosView::SHOW_TYPE type)
{
    current_show_type = type;
    updateShow(currenShowFileName);
}

//获取当前显示的文件名称
QString &PosView::getCurrentShowFileName()
{
    return currenShowFileName;
}

//删除文件对应的pos
bool PosView::deletePointByFile(QString &fn)
{
    if( posList.keys().contains(fn) ){
        posList.remove(fn);
    }

    return true;
}

//删除所有pos
bool PosView::deletePoints()
{
    QStringList ll = posList.keys();
    int len = ll.length();

    for( int i=0; i<len; ++i ){
        posList.remove(ll[i]);
    }

    emit fileListChange(true);

    return true;
}

//更新显示序号
bool PosView::showNumber(bool enable)
{
    if( enable==numShowEnable ) return true;

    numShowEnable = enable;

    updateShow(currenShowFileName);

    return true;
}

//获取当前位置map   文件名:位置信息
QMap<QString, PosFileInfo> &PosView::getPos()
{
    return posList;
}

//获取鼠标当前位置
QString PosView::getMouseUpMsg()
{
    QGraphicsItem *item = itemAt(static_cast<int>(mouseCurrentPoint.x()), static_cast<int>(mouseCurrentPoint.y()));
    int len = ellipseItems.count();
    int itemIndex = INT_MAX;

    for( int i=0; i<len; ++i ){
        if( item==ellipseItems[i] ){
            itemIndex = i;
            break;
        }
    }

    if( itemIndex!=INT_MAX ){
        PosFileInfo info = posList[currenShowFileName];
        QMap<QString, QPointF> points = info.getPoints();

        QString key = points.keys()[itemIndex+1];
        QPointF p   = points[key];

        //qDebug()<<"Key = "<<key<<"; "<<p;
        QStringList ll = key.split("-", QString::SkipEmptyParts);
        QString fm = ">>> %1(%2) %3 %4";

        return fm.arg(ll[2]).arg(ll[3]).arg(ll[0]).arg(ll[1]);
    }

    return "";

}
